import {setToken,getToken,removeToken, setUsername,getUsername,removeUsername} from "@/utils/cookiesCar.js";
import { Register,Login,Forget } from "@/api/account.js";

const state = {
  tokenkey: "" ||getToken(), // 浏览器刷新后vuex数据会丢失，所以可以从cookie中拿
  username: "" || getUsername(), // 浏览器刷新后vuex数据会丢失，所以可以从cookie中拿
};
const mutations = {
  SET_TOKEN(state, val) {
    state.tokenkey = val;
  },
  SET_USERAME(state, val) {
    state.username = val;
  }
};
const actions = {
  // 注册
  registerAction(context,params) {
    return new Promise((resolve, reject) => {
      Register(params).then((res) => {
        resolve(res);
      }).catch((err) => {
        reject(err);
      })
    })
  },
  // 登录
  loginAction(context,params) {
    return new Promise((resolve, reject) => {
      Login(params).then((res) => {
        const data = res.data;
        context.commit("SET_TOKEN",data.token);
        context.commit("SET_USERAME",data.username);
        setToken(data.token);
        setUsername(data.username);
        resolve(res);
      }).catch((err) => {
        reject(err);
      })
    })
  },
  // 退出
  logoutAction(context) {
    return new Promise((resolve) => {
      context.commit("SET_TOKEN","");
      context.commit("SET_USERAME","");
      removeToken();
      removeUsername();
      resolve();
    })
  },
  // 忘记密码
  forgetAction(context,params) {
    return new Promise((resolve,reject) => {
      Forget(params).then((res) => {
        resolve(res);
      }).catch((err) => {
        reject(err);
      })
    })
  }
};
const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}